package cn.lcl.filter;

import cn.lcl.bean.ThreadLocalPageBean;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 分页过滤器
 * Created by licho on 2017/8/17 0017.
 */
@WebFilter(value = "/*",initParams = {@WebInitParam(name="pageSize",value = "10"),@WebInitParam(name="pageIndex",value="1")})
public class PageFilter implements Filter {
    private int pageSize=0;
    private int pageIndex=0;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        pageSize=Integer.parseInt(filterConfig.getInitParameter("pageSize"));//默认的分页大小
        pageIndex=Integer.parseInt(filterConfig.getInitParameter("pageIndex"));//默认显示的页数.
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        int pageIndex=this.pageIndex;
        int pageSize=this.pageSize;
        try{
            HttpServletRequest req=(HttpServletRequest) request;
            HttpServletResponse resp=(HttpServletResponse)response;
            if(req.getParameter("pageIndex")!=null){
                try{pageIndex=Integer.parseInt(req.getParameter("pageIndex"));}catch (Exception e){}
            }
            if(req.getParameter("pageSize")!=null) {
                try {
                    pageSize = Integer.parseInt(req.getParameter("pageSize"));
                } catch (Exception e) {}
            }
            ThreadLocalPageBean.setPageIndex(pageIndex);//将信息不通过内置对象传递到后台
            ThreadLocalPageBean.setPageSize(pageSize);
            chain.doFilter(req, resp);//将请求继续传递
        }finally{
            ThreadLocalPageBean.removePageIndex();
            ThreadLocalPageBean.removePageSize();
        }
    }

    @Override
    public void destroy() {
        System.out.println("PagesFilter destory!");
    }
}
